import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {HttpStatus} from '../enums/http.status';
import {Message, MessageService} from 'primeng/api';
import {TranslateService} from '@ngx-translate/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable({
    providedIn: 'root'
})
export class PermissionInterceptor implements HttpInterceptor {

    constructor(
        protected messageService: MessageService,
        protected translate: TranslateService) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).catch((err: any) => {
            if (err instanceof HttpErrorResponse) {
                switch (err.status) {
                    case HttpStatus.METHOD_NOT_ALLOWED:
                        this.printError('commons.permission.msg.1');
                        break;
                    case HttpStatus.FORBIDDEN:
                        this.printError('commons.permission.msg.2');
                        break;
                    case HttpStatus.UNAUTHORIZED:
                        this.printError('commons.permission.msg.3');
                        location.href = location.href.substring(0, location.href.indexOf('#'));
                        break;
                    default:
                        break;
                }
                return throwError(err);
            }
        });
    }

    private printError(msgKey: string) {
        this.messageService.clear();
        this.messageService.add(<Message>{
            key: 'sys_msg',
            severity: 'error',
            summary: this.translate.instant('commons.error'),
            detail: this.translate.instant(msgKey),
        });
    }
}
